package org.mozhu.mboot.core.data.filter;

import org.apache.commons.lang3.StringUtils;
import org.mozhu.mboot.core.data.SearchFilters;

import java.util.Arrays;

public class SimpleSearchFilter implements SearchFilter {

	private String propertyName;
	private Object value;
	private Object[] values;
	private Operator operator;

	public SimpleSearchFilter(String fieldName, Operator operator, Object value) {
		this.propertyName = fieldName;
		this.operator = operator;
		if (operator == Operator.IN) {
			this.values = StringUtils.split(value.toString(), ",; ");
		} else {
			this.value = value;
		}
	}

	public SimpleSearchFilter(String fieldName, Operator operator, Object[] values) {
		this.propertyName = fieldName;
		this.values = values;
		this.operator = operator;
	}

	public String getPropertyName() {
		return propertyName;
	}

	public Object getValue() {
		return value;
	}

	public Operator getOperator() {
		return operator;
	}

	public Object[] getValues() {
		return values;
	}

	public String getKey() {
		return SearchFilters.getKey(propertyName, operator);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((operator == null) ? 0 : operator.hashCode());
		result = prime * result + ((propertyName == null) ? 0 : propertyName.hashCode());
		result = prime * result + ((value == null) ? 0 : value.hashCode());
		result = prime * result + Arrays.hashCode(values);
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		SimpleSearchFilter other = (SimpleSearchFilter) obj;
		if (operator != other.operator)
			return false;
		if (propertyName == null) {
			if (other.propertyName != null)
				return false;
		} else if (!propertyName.equals(other.propertyName))
			return false;
		if (value == null) {
			if (other.value != null)
				return false;
		} else if (!value.equals(other.value))
			return false;
		if (!Arrays.equals(values, other.values))
			return false;
		return true;
	}

}
